<template>
	<div class="container">
		<select v-model="province" @change="provinceChange">
			<option v-for="(opt,i) in provinceOptions" :key="i"
			:value="opt">{{opt}}</option>
		</select>
		<select v-model="city" @change="cityChange">
			<option v-for="(opt,i) in cityOptions" :key="i"
			:value="opt">{{opt}}</option>
		</select>
		<select v-model="district" @change="districtChange">
			<option v-for="(opt,i) in districtOptions" :key="i"
			:value="opt">{{opt}}</option>
		</select>
	</div>
</template>
<script>
import area from '@/assets/lib/areas.json'
export default{
	name:'AddressSelector',
	created(){
        this.initialize(this.address)
	},
	data(){
		return {
			initializing: false,
			province: '',
			city: '',
            district: '',
            test: [1, 2, 3, 4],
            test2: {a:'sss', b:'xxx'}
		}
	},
	model: {
	   prop: 'address',
	   event: 'addressChange'
	},
	computed:{
		provinceOptions() {
			return Object.keys(area)
		},
		cityOptions() {
			// 省份错误 自动更正为第一省份
			if(!area[this.province]) this.province = this.provinceOptions[0]
			return Object.keys(area[this.province])
		},
		districtOptions() {
			// 城市错误 自动更正为第一城市
			if(!area[this.province][this.city]) this.city = this.cityOptions[0]
			return area[this.province][this.city]
		},
		whole() {
			return {
				province: this.province,
				city: this.city,
				district: this.district
			}
		}
	},
	methods:{
		initialize({province, city, district}) {
			this.province = province || this.provinceOptions[0]
			this.city = city ||  this.cityOptions[0]
            this.district = district ||  this.districtOptions[0]
            // 不然如果初次不选择 地址会为0
            this.$emit('addressChange', this.whole)
		},
		provinceChange(){
			console.log('手动选择省份')
			const cities = area[this.province]
			this.city = Object.keys(cities)[0]
			this.district = area[this.province][this.city][0]
			this.$emit('addressChange', this.whole)
		},
		cityChange(){
			console.log('手动选择城市')
			this.district = area[this.province][this.city][0]
			this.$emit('addressChange', this.whole)
		},
		districtChange(){
			console.log('手动选择地区')
			this.$emit('addressChange', this.whole)
		}
	},
	watch:{
		address(value){
			// 问题是其实每次视图内容更改 引发父级的绑定数据更改 address改变 那这里也会再次触发的…
			this.initialize(value)
		}
	},
	props:{
		address: {
			default: {province:'', city: '', district: ''}
		}
	}
}
</script>
<style lang='less' scoped>
.container{
	display: inline-block;
	select {
		font-size: .35rem;
		width: 1.5rem;
	}
}
</style>
